package com.idlecode.panel.tool;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.Messages;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;

/**
 * @program: IdleCode
 * @description 今日油价
 * @author: rongjuwei
 * @create: 2024-11-18 10:53
 **/
public class TodayOilPricesPanel extends JPanel {

    private static final String app_id = "gnnzinnltnpvfumj";

    private static final String app_secret = "uf3Od4VHXkqLC4y4BgoQrcZdun4rsDwB";

    private static final String url = "https://www.mxnzp.com/api/oil/search?province={}&app_id={}&app_secret={}";

    private JTextField zeroTextField;

    private JTextField eightyNineTextField;

    private JTextField ninetyTwoTextField;

    private JTextField ninetyFiveTextField;

    private JTextField ninetyEightTextField;

    public TodayOilPricesPanel() {
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        //省份
        JPanel provincePanel = new JPanel();
        provincePanel.setLayout(new BoxLayout(provincePanel, BoxLayout.X_AXIS));
        provincePanel.add(Box.createRigidArea(new Dimension(20, 0)));
        provincePanel.add(new JLabel("省份："));
        String[] provinceOptions = {"安徽", "北京", "重庆", "福建", "甘肃", "广东", "广西", "贵州", "海南", "河北",
                "黑龙江", "河南", "湖北", "湖南", "江苏", "江西", "吉林", "辽宁", "内蒙古", "宁夏", "青海", "陕西",
                "上海", "山东", "山西", "四川", "天津", "西藏", "新疆", "云南", "浙江"};
        ComboBox provinceComboBox = new ComboBox<>(provinceOptions);
        provinceComboBox.setMaximumSize(new Dimension(100, 30));
        provincePanel.add(provinceComboBox);
        provincePanel.add(Box.createRigidArea(new Dimension(60, 0)));
        JButton inquireButton = new JButton("查询");
        provincePanel.add(inquireButton);
        inquireButton.addActionListener(e -> {
            String selectedItem = (String) provinceComboBox.getSelectedItem();
            zeroTextField.setText(null);
            eightyNineTextField.setText(null);
            ninetyTwoTextField.setText(null);
            ninetyFiveTextField.setText(null);
            ninetyEightTextField.setText(null);
            new Task.Backgroundable(null, "Fetching Oil Prices", false) {
                @Override
                public void run(@NotNull ProgressIndicator indicator) {

                    OkHttpClient client = new OkHttpClient();

                    Request request = new Request.Builder()
                            .url(StrUtil.format(url, selectedItem, app_id, app_secret))
                            .addHeader("Accept", "application/json")
                            .build();

                    try (Response response = client.newCall(request).execute()) {
                        if (response.isSuccessful() && response.body() != null) {
                            String responseStr = response.body().string();
                            ObjectMapper mapper = new ObjectMapper();
                            // 将字符串解析为JsonNode
                            JsonNode jsonNode = mapper.readTree(responseStr);
                            String code = jsonNode.get("code").asText();
                            if ("1".equals(code)) {
                                JsonNode dataJsonNode = jsonNode.get("data");
                                String t0 = dataJsonNode.get("t0").asText();
                                zeroTextField.setText(t0);
                                String t89 = dataJsonNode.get("t89").asText();
                                eightyNineTextField.setText(t89);
                                String t92 = dataJsonNode.get("t92").asText();
                                ninetyTwoTextField.setText(t92);
                                String t95 = dataJsonNode.get("t95").asText();
                                ninetyFiveTextField.setText(t95);
                                String t98 = dataJsonNode.get("t98").asText();
                                ninetyEightTextField.setText(t98);
                            } else {
                                // 使用 invokeLater 确保 UI 操作在 EDT 中执行
                                ApplicationManager.getApplication().invokeLater(() ->
                                        Messages.showMessageDialog(jsonNode.get("msg").asText(), "错误", Messages.getErrorIcon())
                                );
                            }
                        }
                    } catch (Exception ex) {
                        // 使用 invokeLater 确保 UI 操作在 EDT 中执行
                        ApplicationManager.getApplication().invokeLater(() ->
                                Messages.showMessageDialog(ex.getMessage(), "错误", Messages.getErrorIcon())
                        );
                    }
                }
            }.queue();
        });

        provincePanel.add(Box.createHorizontalGlue()); // 右侧弹性空间
        this.add(provincePanel);

        //0号
        JPanel zeroPanel = new JPanel();
        zeroPanel.setLayout(new BoxLayout(zeroPanel, BoxLayout.X_AXIS));
        zeroPanel.add(Box.createRigidArea(new Dimension(28, 0)));
        zeroPanel.add(new JLabel("0#："));
        zeroTextField = new JTextField();
        zeroTextField.setPreferredSize(new Dimension(150, 30));
        zeroTextField.setMinimumSize(new Dimension(150, 30));
        zeroTextField.setMaximumSize(new Dimension(150, 30));
        zeroPanel.add(zeroTextField);
        zeroPanel.add(new JLabel("元/升"));
        zeroPanel.add(Box.createHorizontalGlue()); // 右侧弹性空间
        this.add(zeroPanel);

        //89号
        JPanel eightyNinePanel = new JPanel();
        eightyNinePanel.setLayout(new BoxLayout(eightyNinePanel, BoxLayout.X_AXIS));
        eightyNinePanel.add(Box.createRigidArea(new Dimension(20, 0)));
        eightyNinePanel.add(new JLabel("89#："));
        eightyNineTextField = new JTextField();
        eightyNineTextField.setPreferredSize(new Dimension(150, 30));
        eightyNineTextField.setMinimumSize(new Dimension(150, 30));
        eightyNineTextField.setMaximumSize(new Dimension(150, 30));
        eightyNinePanel.add(eightyNineTextField);
        eightyNinePanel.add(new JLabel("元/升"));
        eightyNinePanel.add(Box.createHorizontalGlue()); // 右侧弹性空间
        this.add(eightyNinePanel);

        //92号
        JPanel ninetyTwoPanel = new JPanel();
        ninetyTwoPanel.setLayout(new BoxLayout(ninetyTwoPanel, BoxLayout.X_AXIS));
        ninetyTwoPanel.add(Box.createRigidArea(new Dimension(20, 0)));
        ninetyTwoPanel.add(new JLabel("92#："));
        ninetyTwoTextField = new JTextField();
        ninetyTwoTextField.setPreferredSize(new Dimension(150, 30));
        ninetyTwoTextField.setMinimumSize(new Dimension(150, 30));
        ninetyTwoTextField.setMaximumSize(new Dimension(150, 30));
        ninetyTwoPanel.add(ninetyTwoTextField);
        ninetyTwoPanel.add(new JLabel("元/升"));
        ninetyTwoPanel.add(Box.createHorizontalGlue()); // 右侧弹性空间
        this.add(ninetyTwoPanel);

        //95号
        JPanel ninetyFivePanel = new JPanel();
        ninetyFivePanel.setLayout(new BoxLayout(ninetyFivePanel, BoxLayout.X_AXIS));
        ninetyFivePanel.add(Box.createRigidArea(new Dimension(20, 0)));
        ninetyFivePanel.add(new JLabel("95#："));
        ninetyFiveTextField = new JTextField();
        ninetyFiveTextField.setPreferredSize(new Dimension(150, 30));
        ninetyFiveTextField.setMinimumSize(new Dimension(150, 30));
        ninetyFiveTextField.setMaximumSize(new Dimension(150, 30));
        ninetyFivePanel.add(ninetyFiveTextField);
        ninetyFivePanel.add(new JLabel("元/升"));
        ninetyFivePanel.add(Box.createHorizontalGlue()); // 右侧弹性空间
        this.add(ninetyFivePanel);

        //98号
        JPanel ninetyEightPanel = new JPanel();
        ninetyEightPanel.setLayout(new BoxLayout(ninetyEightPanel, BoxLayout.X_AXIS));
        ninetyEightPanel.add(Box.createRigidArea(new Dimension(20, 0)));
        ninetyEightPanel.add(new JLabel("98#："));
        ninetyEightTextField = new JTextField();
        ninetyEightTextField.setPreferredSize(new Dimension(150, 30));
        ninetyEightTextField.setMinimumSize(new Dimension(150, 30));
        ninetyEightTextField.setMaximumSize(new Dimension(150, 30));
        ninetyEightPanel.add(ninetyEightTextField);
        ninetyEightPanel.add(new JLabel("元/升"));
        ninetyEightPanel.add(Box.createHorizontalGlue()); // 右侧弹性空间
        this.add(ninetyEightPanel);
    }
}
